﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Yu.Cms.Common;
using Yu.Cms.IDAL;
using Yu.Enum;

namespace Yu.Cms.SQLServerDAL
{
    public class Content : IContent
    {
        private readonly string TableName = "Y_Content";

        #region IContent 成员


        /// <summary>
        /// 是否存在小类
        /// </summary>
        /// <param name="SmallTypeID"></param>
        /// <returns></returns>
        public bool ExistSmallTypeID(int SmallTypeID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from  " + TableName);
            strSql.Append(" where SmallTypeID=@SmallTypeID ");
            SqlParameter[] parameters = {
					new SqlParameter("@SmallTypeID", SqlDbType.Int,4)};
            parameters[0].Value = SmallTypeID;
            return DbHelperMsSQL.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Yu.Cms.Model.Content model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into "+TableName+"(");
            strSql.Append("BigTypeID,SmallTypeID,Title,aContent,CommentCount,AllowTop,AllowHot,AllowComment,AllowShow,ViewCount,PubTime,aKey)");
            strSql.Append(" values (");
            strSql.Append("@BigTypeID,@SmallTypeID,@Title,@aContent,@CommentCount,@AllowTop,@AllowHot,@AllowComment,@AllowShow,@ViewCount,@PubTime,@aKey)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@BigTypeID", SqlDbType.Int,4),
					new SqlParameter("@SmallTypeID", SqlDbType.Int,4),
					new SqlParameter("@Title", SqlDbType.NVarChar,100),
					new SqlParameter("@aContent", SqlDbType.NText),
					new SqlParameter("@CommentCount", SqlDbType.Int,4),
					new SqlParameter("@AllowTop", SqlDbType.Bit,1),
					new SqlParameter("@AllowHot", SqlDbType.Bit,1),
					new SqlParameter("@AllowComment", SqlDbType.Bit,1),
					new SqlParameter("@AllowShow", SqlDbType.Bit,1),
					new SqlParameter("@ViewCount", SqlDbType.Int,4),
					new SqlParameter("@PubTime", SqlDbType.SmallDateTime),
					new SqlParameter("@aKey", SqlDbType.NVarChar,50)};
            parameters[0].Value = model.BigTypeID;
            parameters[1].Value = model.SmallTypeID;
            parameters[2].Value = model.Title;
            parameters[3].Value = model.aContent;
            parameters[4].Value = model.CommentCount;
            parameters[5].Value = model.AllowTop;
            parameters[6].Value = model.AllowHot;
            parameters[7].Value = model.AllowComment;
            parameters[8].Value = model.AllowShow;
            parameters[9].Value = model.ViewCount;
            parameters[10].Value = model.PubTime;
            parameters[11].Value = model.aKey;

            object obj = DbHelperMsSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return -1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(Yu.Cms.Model.Content model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + TableName + " set ");
            strSql.Append("BigTypeID=@BigTypeID,");
            strSql.Append("SmallTypeID=@SmallTypeID,");
            strSql.Append("Title=@Title,");
            strSql.Append("aContent=@aContent,");
            strSql.Append("CommentCount=@CommentCount,");
            strSql.Append("AllowTop=@AllowTop,");
            strSql.Append("AllowHot=@AllowHot,");
            strSql.Append("AllowComment=@AllowComment,");
            strSql.Append("AllowShow=@AllowShow,");
            strSql.Append("ViewCount=@ViewCount,");
            strSql.Append("PubTime=@PubTime,");
            strSql.Append("aKey=@aKey");
            strSql.Append(" where PostID=@PostID ");
            SqlParameter[] parameters = {
					new SqlParameter("@PostID", SqlDbType.Int,4),
					new SqlParameter("@BigTypeID", SqlDbType.Int,4),
					new SqlParameter("@SmallTypeID", SqlDbType.Int,4),
					new SqlParameter("@Title", SqlDbType.NVarChar,100),
					new SqlParameter("@aContent", SqlDbType.NText),
					new SqlParameter("@CommentCount", SqlDbType.Int,4),
					new SqlParameter("@AllowTop", SqlDbType.Bit,1),
					new SqlParameter("@AllowHot", SqlDbType.Bit,1),
					new SqlParameter("@AllowComment", SqlDbType.Bit,1),
					new SqlParameter("@AllowShow", SqlDbType.Bit,1),
					new SqlParameter("@ViewCount", SqlDbType.Int,4),
					new SqlParameter("@PubTime", SqlDbType.SmallDateTime),
					new SqlParameter("@aKey", SqlDbType.NVarChar,50)};
            parameters[0].Value = model.PostID;
            parameters[1].Value = model.BigTypeID;
            parameters[2].Value = model.SmallTypeID;
            parameters[3].Value = model.Title;
            parameters[4].Value = model.aContent;
            parameters[5].Value = model.CommentCount;
            parameters[6].Value = model.AllowTop;
            parameters[7].Value = model.AllowHot;
            parameters[8].Value = model.AllowComment;
            parameters[9].Value = model.AllowShow;
            parameters[10].Value = model.ViewCount;
            parameters[11].Value = model.PubTime;
            parameters[12].Value = model.aKey;

            return DbHelperMsSQL.ExecuteSql(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 根据文章ID删除文章内容
        /// </summary>
        /// <param name="PostID">1,2,3,4</param>
        /// <returns></returns>
        public int Delete(string PostID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from  " + TableName);
            strSql.AppendFormat(" where PostID in ({0}) ",PostID);           
            return DbHelperMsSQL.ExecuteSql(strSql.ToString());
        }

        /// <summary>
        /// 批量置顶
        /// </summary>
        /// <param name="PostID">2,4,6</param>
        /// <returns></returns>
        public void SetTopOnOff(string PostID, bool isTop)
        {

            string strWhere = "  PostID in (" + PostID + " )";
            string Table_FiledsValue = "";
            if (isTop)
            {
                Table_FiledsValue = " AllowTop=1";
            }
            else
            {
                Table_FiledsValue = " AllowTop=0";
            }
            DbHelperMsSQL.Update_Table_Fileds(TableName, Table_FiledsValue, strWhere);
        }
 
        /// <summary>
        /// 批量移动
        /// </summary>
        /// <param name="PostID"></param>
        /// <returns></returns>
        public void MoveClass(string PostID, int BigTypeID, int SmallTypeID)
        {
            string strWhere = "  PostID in (" + PostID + " )";
            string Table_FiledsValue = string.Format(" BigTypeID={0},SmallTypeID={1}", BigTypeID, SmallTypeID);
            DbHelperMsSQL.Update_Table_Fileds(TableName, Table_FiledsValue, strWhere);
        }
        /// <summary>
        /// 根据文章ID获取文章内容
        /// </summary>
        /// <param name="PostID"></param>
        /// <returns></returns>
        public Yu.Cms.Model.Content GetModel(int PostID)
        {
            QueryParam qp = new QueryParam();
            Yu.Cms.Model.Content fam = new Yu.Cms.Model.Content();
            qp.Where = " Where PostID=" + PostID;
            int RecordCount;
            IList<Yu.Cms.Model.Content> lst = this.GetList(qp, out RecordCount);
            if (lst.Count > 0)
            {
                fam = lst[0];
            }
            return fam;
        }

        /// <summary>
        /// 根据文章ID获取上一篇或下一篇文章内容
        /// </summary>
        /// <param name="PostID">文章ID</param>
        /// <param name="BigTypeID">文章大类</param>
        /// <param name="iSort">UP，上一篇文章， Donw，下一篇文章</param>
        /// <returns></returns>
        public Yu.Cms.Model.Content GetPrevNextModel(int PostID, int BigTypeID, Sort iSort)
        {
            QueryParam qp = new QueryParam();
            Yu.Cms.Model.Content fam = new Yu.Cms.Model.Content();
            qp.Orderfld = "PostID";
            qp.PageSize = 1;
            qp.PageIndex = 1;
            if (iSort == Sort.up)
            {
                qp.Where = string.Format(" Where   PostID>{0} And BigTypeID={1}", PostID, BigTypeID);
                qp.OrderType = 0;
             }
            else if (iSort == Sort.down)
            {
                qp.Where = string.Format(" Where   PostID<{0} And BigTypeID={1}", PostID, BigTypeID);
                qp.OrderType = 1;
            }
            else
            {
                return null;
            }
            int RecordCount;
            IList<Yu.Cms.Model.Content> lst = this.GetList(qp, out RecordCount);
            if (lst.Count > 0)
            {
                fam = lst[0];
            }
            return fam;
        }

        /// <summary>
        /// 获取置顶文章列表
        /// </summary>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetTopList(int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageSize = iTop;
            qp.PageIndex = 1;
            qp.OrderType = 1;            
            qp.Where = " Where AllowTop=1";
            int RecordCount;
            return this.GetList(qp, out RecordCount);
        }



        /// <summary>
        /// 获取热门文章列表
        /// </summary>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetHotList(int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageSize = iTop;
            qp.PageIndex = 1;
            qp.OrderType = 1;
            qp.Orderfld = " ViewCount";
            int RecordCount;
            return this.GetList(qp, out RecordCount);

        }

        /// <summary>
        /// 获取热评文章列表
        /// </summary>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetHotCommentList(int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageSize = iTop;
            qp.PageIndex = 1;
            qp.OrderType = 1;
            qp.Orderfld = " CommentCount";
            int RecordCount;
            return this.GetList(qp, out RecordCount);
        }


        /// <summary>
        /// 获取最新文章文章
        /// </summary>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetNewList(int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageSize = iTop;
            qp.PageIndex = 1;
            qp.OrderType = 1;
            int RecordCount;
            return this.GetList(qp, out RecordCount);
        }

        /// <summary>
        /// 根据小类ID获取最新文章文章
        /// </summary>
        /// <param name="SmallTypeID">小类ID</param>
        /// <param name="iTop">首页显示iTop条</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetNewList(int SmallTypeID, int iTop)
        {
            QueryParam qp = new QueryParam();
            qp.PageSize = iTop;
            qp.PageIndex = 1;
            qp.OrderType = 1;
            qp.Where = " Where SmallTypeID=" + SmallTypeID;
            int RecordCount;
            return this.GetList(qp, out RecordCount);
        }



        /// <summary>
        /// 评论次数+1;
        /// 或评论次数-1;
        /// </summary>
        /// <param name="PostID"></param>
        public void UpdateContentComment(int PostID, Yu.Enum.AddSub AddSub)
        {
            if (AddSub == Yu.Enum.AddSub.Add)
            {
                DbHelperMsSQL.Update_Table_Fileds(TableName, " CommentCount=CommentCount+1 ", " PostID=" + PostID);
            }
            else if(AddSub == Yu.Enum.AddSub.Sub)
            {
                DbHelperMsSQL.Update_Table_Fileds(TableName, " CommentCount=CommentCount-1 ", " PostID=" + PostID);
            }
        }

        /// <summary>
        /// 点击次数+1
        /// </summary>
        /// <param name="PostID"></param>
        public void UpdateViewCount(int PostID)
        {
            DbHelperMsSQL.Update_Table_Fileds(TableName, " ViewCount=ViewCount+1 ", " PostID=" + PostID);
        }
        /// <summary>
        ///  根据大类查找所有文章（带分页）
        /// </summary>
        /// <param name="BigTypeID">大类ID</param>
        /// <param name="CurrentPageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>      
        /// <param name="RecordCount">返回记录数</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetListByBigType(int BigTypeID, int CurrentPageIndex, int PageSize, out int RecordCount)
        {
            QueryParam qp = new QueryParam();
            qp.PageIndex = CurrentPageIndex;
            qp.PageSize = PageSize;
            if (BigTypeID != 0)
            {
                qp.Where = " Where BigTypeID=" + BigTypeID + "";
            }
            qp.Orderfld = " AllowTop";
            qp.OrderType = 1;
            return this.GetList(qp, out RecordCount);
        }

        /// <summary>
        /// 根据小类查找所有文章（带分页）
        /// </summary>
        /// <param name="SmallTypeID">小类ID</param>
        /// <param name="CurrentPageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>      
        /// <param name="RecordCount">返回记录数</param>
        /// <returns></returns>
        public IList<Yu.Cms.Model.Content> GetListBySmallType(int SmallTypeID, int CurrentPageIndex, int PageSize, out int RecordCount)
        {
            QueryParam qp = new QueryParam();
            qp.PageIndex = CurrentPageIndex;
            qp.PageSize = PageSize;
            qp.Where = " Where SmallTypeID=" + SmallTypeID;
            return this.GetList(qp, out RecordCount);
        }
        #endregion

        /// <summary>
        /// 将记录集转为Content实体类 (Y_Content)
        /// </summary>
        /// <param name="dr">记录集</param>
        /// <param name="Fileds">字段名列表</param>
        /// <returns>Content</returns>
        protected Yu.Cms.Model.Content Populate_Content(IDataReader dr, Dictionary<string, string> Fileds)
        {
            Yu.Cms.Model.Content nc = new Yu.Cms.Model.Content();
            if (Fileds.ContainsKey("PostID") && !Convert.IsDBNull(dr["PostID"])) nc.PostID = Convert.ToInt32(dr["PostID"]); // PostID
            if (Fileds.ContainsKey("BigTypeID") && !Convert.IsDBNull(dr["BigTypeID"])) nc.BigTypeID = Convert.ToInt32(dr["BigTypeID"]); // BigTypeID
            if (Fileds.ContainsKey("SmallTypeID") && !Convert.IsDBNull(dr["SmallTypeID"])) nc.SmallTypeID = Convert.ToInt32(dr["SmallTypeID"]); // SmallTypeID
            if (Fileds.ContainsKey("Title") && !Convert.IsDBNull(dr["Title"])) nc.Title = Convert.ToString(dr["Title"]).Trim(); // Title
            if (Fileds.ContainsKey("aContent") && !Convert.IsDBNull(dr["aContent"])) nc.aContent = Convert.ToString(dr["aContent"]).Trim(); // aContent
            if (Fileds.ContainsKey("CommentCount") && !Convert.IsDBNull(dr["CommentCount"])) nc.CommentCount = Convert.ToInt32(dr["CommentCount"]); // CommentCount
            if (Fileds.ContainsKey("AllowTop") && !Convert.IsDBNull(dr["AllowTop"])) nc.AllowTop = Convert.ToBoolean(dr["AllowTop"]); // 是否置顶
            if (Fileds.ContainsKey("AllowHot") && !Convert.IsDBNull(dr["AllowHot"])) nc.AllowHot = Convert.ToBoolean(dr["AllowHot"]); // 是否热门
            if (Fileds.ContainsKey("AllowComment") && !Convert.IsDBNull(dr["AllowComment"])) nc.AllowComment = Convert.ToBoolean(dr["AllowComment"]); // 是否允许评论
            if (Fileds.ContainsKey("AllowShow") && !Convert.IsDBNull(dr["AllowShow"])) nc.AllowShow = Convert.ToBoolean(dr["AllowShow"]); // 是否允许显示
            if (Fileds.ContainsKey("ViewCount") && !Convert.IsDBNull(dr["ViewCount"])) nc.ViewCount = Convert.ToInt32(dr["ViewCount"]); // 点击次数
            if (Fileds.ContainsKey("PubTime") && !Convert.IsDBNull(dr["PubTime"])) nc.PubTime = Convert.ToDateTime(dr["PubTime"]); // PubTime
            if (Fileds.ContainsKey("aKey") && !Convert.IsDBNull(dr["aKey"])) nc.aKey = Convert.ToString(dr["aKey"]).Trim(); // 搜索关键字
            return nc;
        }


        /// <summary>
        /// 返回Content实体类的IList对象 (Y_Content)
        /// </summary>
        /// <param name="qp">查询类(非安全函数,传入参数请进行Sql字符串过滤)</param>
        /// <param name="RecordCount">返回记录总数</param>
        /// <returns>Content实体类的IList对象(Y_Content)</returns>
        public IList<Yu.Cms.Model.Content> GetList(QueryParam qp, out int RecordCount)
        {
            qp.TableName = TableName;
            if (qp.Orderfld == null)
            {
                qp.Orderfld = "PostID";
            }
            else if (qp.Orderfld != "PostID")
            {
                qp.Orderfld += ",PostID";
            }

            if (qp.ReturnFields == null)
            {
                qp.ReturnFields = "*";
            }
            else
            {
                qp.ReturnFields += ",";
                qp.ReturnFields += qp.Orderfld;
            }
            DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Content> mypd = new DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Content>(this.Populate_Content);
            return DbHelperMsSQL.GetRecordListBySql(mypd, qp, out RecordCount);
        }

    }
}
